/*
 * verifier.cpp
 *
 *  Created on: Mar 19, 2017
 *      Author: hp
 */

#include <iostream>

#include "macaroon.h"

namespace c_macaroons {
#include "macaroons.h"
}

namespace macaroons {

verifier::verifier() {
	v = c_macaroons::macaroon_verifier_create();
}

void verifier::satisfy_exact(const std::string predicate) {
	c_macaroons::macaroon_returncode err = c_macaroons::MACAROON_SUCCESS;

	c_macaroons::macaroon_verifier_satisfy_exact(v,
			(const unsigned char*) predicate.data(), predicate.size(), &err);
}

bool verifier::verify(const macaroon& m, const std::string key) const {
	c_macaroons::macaroon_returncode err = c_macaroons::MACAROON_SUCCESS;

	int rc = c_macaroons::macaroon_verify(v, m.m,
			(const unsigned char*) key.data(), key.size(), NULL, 0, &err);

	if (rc == 0)
		return true;

	return false;
}

bool verifier::verify(const macaroon& m, const std::string key,
		macaroon_list third_party_caveats) const {
	c_macaroons::macaroon_returncode err = c_macaroons::MACAROON_SUCCESS;

	c_macaroons::macaroon** MS =
			new c_macaroons::macaroon*[third_party_caveats.size()];

	for (size_t i = 0; i < third_party_caveats.size(); ++i) {
		MS[i] = third_party_caveats[i].m;
	}

	int rc = c_macaroons::macaroon_verify(v, m.m,
			(const unsigned char*) key.data(), key.size(), MS,
			third_party_caveats.size(), &err);

	delete[] MS;

	if (rc == 0)
		return true;

	return false;
}

verifier::~verifier() {
	c_macaroons::macaroon_verifier_destroy(v);
}

} // namespace macaroons
